package com.nexfra.vocsys.common.interceptor;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.nexfra.vocsys.common.Constants;
import com.nexfra.vocsys.common.domain.User;

public class SessionIntercepter extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory
			.getLogger(SessionIntercepter.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) {
		String servletPath = "main";
		logger.info("<==========================================");
		logger.info("-ServletPath:"+request.getServletPath());
		logger.info("-RequestURL:"+request.getRequestURL());
		logger.info("-RequestURI:"+request.getRequestURI());
		logger.info("==========================================>");
		try {
			// false옵션: session 객체가 생성된 경우에는 session 객체를 리턴하고 
			// session 객체가 생성되어 있지 않은 경우에는 null을 리턴한다.
			HttpSession session = request.getSession(true);
  			
logger.info("session.isNew():"+session.isNew());			
logger.info("session.getAttribute('userInfo'):"+session.getAttribute(Constants.USER_KEY));
			
			if(request.getServletPath().endsWith("main")) { // 메인페이지 uri 호출인 경우
				return true;
			} 
			else if(request.getServletPath().endsWith("main/mainframe")) { // 메인프레임
				return true;
			}
			else if(request.getServletPath().endsWith("common/sessionRedirect")) {
				return true;
			}	
			else {
				User user = (User)session.getAttribute(Constants.USER_KEY);
				/*if(user == null || "".equals(user.getUserId())) {
					// session non exist
					logger.info("User object in session object is null!");		
					response.sendRedirect(request.getContextPath()+"/common/sessionRedirect");
					return false;
				}*/
				//@테스트용 임시 세션 생성
				{
					user = new User();
					user.setComId("HANABANK");
					user.setUserId("admin");
					user.setUserName("");
					user.setUserDeptId("");
					user.setUserDeptName("");
					user.setComId("HANABANK");
					session.setAttribute(Constants.USER_KEY, user);
					session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.KOREAN);
				}
			}

			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}
	}
}
